﻿<script setup>

import { onMounted, ref } from 'vue'

import { queryAllCourse,queryCourseById, deleteCourse, addCourse,updateCourse} from "@/api/course"

import { ElMessage,ElMessageBox } from 'element-plus'

import {Plus} from '@element-plus/icons-vue'



const form = ref({title:''})

const currentPage = ref(1)

const pageSize = ref(10)

const background = ref(true);

const total = ref(0);

const tableData = ref([])



onMounted(() => {

  search()

})

const search=async ()=>{

  const restult = await queryAllCourse(form.value.title,currentPage.value,pageSize.value)

  console.log(restult)

  if(restult.code){

    tableData.value = restult.data.rows;

    total.value = restult.data.total

  }else{

    ElMessage.error(restult.msg)

  }

}

const handleDelete=async (id)=>{

  ElMessageBox.confirm('您确认删除该课程分类信息吗?','提示',

      { confirmButtonText: '确认',cancelButtonText: '取消',type: 'warning'}

  ).then(async () => {

    const result = await deleteCourse(id)

    if(result.code){

      ElMessage.success("删除成功")

      search()

    }else{

      ElMessage.error("删除失败")

    }

  }).catch(() => {

    ElMessage.info('已取消删除')

  })

}

const selectedIds=ref([])

const handleSelectionChange=(selection)=>{

  selectedIds.value = selection.map(item=>item.id)

}

const deleteCourseByIds=()=>{

  ElMessageBox.confirm('此操作将永久删除该课程信息, 是否继续?', '提示', {

    confirmButtonText: '确定',

    cancelButtonText: '取消',

    type: 'warning'

  }).then(async () => {

    if(selectedIds.value&&selectedIds.value.length>0){

      const ids=selectedIds.value.join(',')

      const result = await deleteCourse(ids)

      if(result.code){

        ElMessage.success("删除成功")

        search()

      }else{

        ElMessage.error("删除失败")

      }

    }else{

      ElMessage.error("已取消删除")

    }

  })

}

const dialogVisible=ref(false)

const dialogTitle=ref("新增课程信息")

const course=ref({

  title:'',

  duration:'',

  materialsCount:null,

  summary:'',

  suitableFor:'',

  images:'',

  videoUrl:'',

  prePrice:null,

  currentPrice:null,

  benefits:'',

  notice:'',

  consultantId:null,

  categoryId:null

})

const saveCourse=()=>{

  dialogVisible.value=true

  dialogTitle.value="新增课程信息"

  course.value={

    title:'',

    duration:'',

    materialsCount:null,

    summary:'',

    suitableFor:'',

    images:'',

    videoUrl:'',

    prePrice:null,

    currentPrice:null,

    benefits:'',

    notice:'',

    consultantId:null,

    categoryId:null

  }

}

const clear=()=>{

  form.title=''

  search()

}

const handleAvatarSuccess=(response)=>{

  if (response.code==1) {

    course.value.images ='http://localhost:8080'+response.data; // 将服务器返回的图片路径绑定到 course.images

    ElMessage.success('上传成功');

  } else {

    ElMessage.error(response.msg || '上传失败');

  }

}

const beforeAvatarUpload=(rawFile)=>{

  const isImage = rawFile.type.startsWith( 'image/');

  // 校验文件类型

  if (!isImage) {

    ElMessage.error('只支持上传 JPG/PNG 格式的图片');

    return false;

  }

  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  // 校验文件大小

  if (!isLt2M) {

    ElMessage.error('图片大小不能超过 10MB');

    return false;

  }

  return true;

}

//视频上传模块

const handleSuccess = (response) => {

  if(response.code){

    course.value.videoUrl='http://localhost:8080'+response.data;

    ElMessage.success("上传成功")

  }else{

    ElMessage.error(response.msg || '上传失败')

  }

};



const handleError = (error) => {

  console.error('上传失败', error);

};



const beforeUpload = (file) => {

  const isVideo = file.type.indexOf('video') > -1;

  const isLt200M = file.size / 1024 / 1024 < 200;



  if (!isVideo) {

    console.error('请上传视频文件');

    return false;

  }

  if (!isLt200M) {

    console.error('视频文件大小不能超过 200MB');

    return false;

  }

  return true;

};



const handleEdit=async(id)=>{

  const result=await queryCourseById(id)

  console.log(result.data);

  if(result.code){

    dialogVisible.value=true;

    dialogTitle.value='修改课程分类'

    course.value = {

      id: result.data.id, // 确保 id 也被设置

      title: result.data.title,

      duration: result.data.duration,

      materialsCount: result.data.materialsCount,

      summary: result.data.summary,

      suitableFor: result.data.suitableFor,

      images: result.data.images,

      videoUrl: result.data.videoUrl,

      prePrice: result.data.prePrice,

      currentPrice: result.data.currentPrice,

      benefits: result.data.benefits,

      notice: result.data.notice,

      consultantId: result.data.consultantId,

      categoryId: result.data.categoryId

    };

  }

}

const save=async()=>{

  let result;

  if(course.value.id){

    result=await updateCourse(course.value)

  }else{

    result=await addCourse(course.value)

  }

  if(result.code){

    ElMessage.success("保存成功")

    dialogVisible.value=false;

    search()

  }else{

    ElMessage.error("保存失败")

    dialogVisible.value=true;

  }

}

const handleSizeChange = (val) => {

  search()

}

const handleCurrentChange = (val) => {

  search()

}

const rules = {

  title: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],

  duration: [{ required: true, message: '请输入课程时长', trigger: 'blur' }],

  summary: [{ required: true, message: '请输入课程简介', trigger: 'blur' }],

  suitableFor: [{ required: true, message: '请输入适用人群', trigger: 'blur' }],

  price: [{ required: true, message: '请输入课程价格', trigger: 'blur' }],

  notice: [{ required: true, message: '请输入订阅须知', trigger: 'blur' }],

  consultantId: [{ required: true, message: '请选择咨询师', trigger: 'change' }],

  categoryId: [{ required: true, message: '请选择课程类型', trigger: 'change' }],

};



const videoDialogVisible = ref(false);

const currentVideoUrl = ref('');



const openVideoDialog = (videoUrl) => {

  currentVideoUrl.value = videoUrl;


  videoDialogVisible.value = true;

};

</script>

<template>

  <h3>课程信息管理</h3>

  <div class="container">

    <el-form :model="form" label-width="auto" style="max-width: 600px">

      <el-form-item label="课程名称">

        <el-input v-model="form.title" clearable @clear="clear" placeholder="请输入课程名称"/>

      </el-form-item>

    </el-form>

    <el-button type="primary" @click="search">查询</el-button>

  </div>

  <el-button type="primary" @click="saveCourse">新增课程</el-button>

  <el-button type="danger" @click="deleteCourseByIds"  >批量删除</el-button>

  <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">

    <el-table-column type="selection" width="55" />

    <el-table-column label="ID" property="id" width="50" />

    <el-table-column label="课程名称" property="title" width="120" />

    <el-table-column label="课程时长" property="duration" width="80" />

    <el-table-column label="课程节数" property="materialsCount" width="80"/>

    <el-table-column label="课程简介" property="summary" width="120" show-overflow-tooltip/>

    <el-table-column label="适用人群" property="suitableFor" width="120" />

    <el-table-column label="课程类型" property="categoryId"  width="120" >

      <template #default="scope">

        <span v-if="scope.row.categoryId == 1">晓兰精选</span>

        <span v-else-if="scope.row.categoryId == 2">社会心理</span>

        <span v-else-if="scope.row.categoryId == 3">心理锻炼</span>

        <span v-else="scope.row.categoryId == 4">成长焦虑</span>

      </template>

    </el-table-column>

    <el-table-column label="课程封面" property="images" width="120" >

      <template #default="scope">

        <img :src="scope.row.images" alt="课程封面" style="width: 100%; height: auto;">

      </template>

    </el-table-column>

    <el-table-column label="课程视频" property="videoUrl"  width="120" >

      <template #default="scope">

        <el-link type="primary" @click="openVideoDialog(scope.row.videoUrl)">查看视频</el-link>

      </template>

    </el-table-column>

    <el-table-column label="学习收获" property="benefits"  width="120" show-overflow-tooltip/>

    <el-table-column label="订阅须知" property="notice"  width="120" show-overflow-tooltip/>

    <el-table-column label="课程原价" property="prePrice"  width="120" />

    <el-table-column label="课程现价" property="currentPrice"  width="120" />

    <el-table-column label="咨询师" property="consultantId"  width="120">

      <template #default="scope">

        <span v-if="scope.row.consultantId == 1">张晓岚</span>

        <span v-else-if="scope.row.consultantId == 2">张广顺</span>

        <span v-else-if="scope.row.consultantId == 3">李雪峰</span>

        <span v-else-if="scope.row.consultantId == 4">季中祥</span>

        <span v-else="scope.row.consultantId == 5">王伟</span>

      </template>

    </el-table-column>

    <el-table-column label="操作" width="160" >

      <template #default="scope">

        <el-button type="info" size="mini" @click="handleEdit(scope.row.id)">编辑</el-button>

        <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>

      </template>

    </el-table-column>

  </el-table>

  <el-pagination

      v-model:current-page="currentPage"

      v-model:page-size="pageSize"

      :page-sizes="[10, 20, 30, 40]"

      :size="size" :disabled="disabled"

      :background="background"

      layout="total, sizes, prev, pager, next, jumper"

      :total="total"

      @size-change="handleSizeChange"

      @current-change="handleCurrentChange" />

  <el-dialog v-model="videoDialogVisible" title="视频播放">

    <video width="100%" height="auto" controls>

      <source :src="currentVideoUrl" type="video/mp4">

    </video>

  </el-dialog>

  <el-dialog v-model="dialogVisible" :title="dialogTitle">

    <el-form :model="course" :rules="rules" ref="courseFormRef" label-width="80px">

      <el-form-item label="课程名称" prop="title">

        <el-input v-model="course.title" placeholder="请输入课程名"></el-input>

      </el-form-item>

      <el-form-item label="课程时长" prop="duration">

        <el-input v-model="course.duration" placeholder="请输入课程时长"></el-input>

      </el-form-item>

      <el-form-item label="课程节数" prop="materialsCount">

        <el-input v-model="course.materialsCount" placeholder="请输入课程节数"></el-input>

      </el-form-item>

      <el-form-item label="课程简介" prop="summary">

        <el-input v-model="course.summary" type="textarea" :rows="2" placeholder="请输入课程简介"></el-input>

      </el-form-item>

      <el-form-item label="学习收获" prop="benefits">

        <el-input v-model="course.benefits" type="textarea" :rows="2" placeholder="请输入学习收获"></el-input>

      </el-form-item>

      <el-form-item label="课程封面" prop="images">

        <el-upload

            class="avatar-uploader"

            action="/api/upload"

            :show-file-list="false"

            :on-success="handleAvatarSuccess"

            :before-upload="beforeAvatarUpload"

        >

          <img v-if="course.images" :src="course.images" class="avatar" />

          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

        </el-upload>

      </el-form-item>

      <el-form-item label="课程视频" prop="videoUrl">

        <el-upload

            action="/api/upload/video"

            :limit="1"

            :on-success="handleSuccess"

            :on-error="handleError"

            :before-upload="beforeUpload"

            accept="video/*"

            drag

        >

          <template #trigger>

            <span>点击上传</span>

          </template>

        </el-upload>

      </el-form-item>

      <el-form-item label="适用人群" prop="suitableFor">

        <el-input v-model="course.suitableFor" placeholder="请输入适用人群"></el-input>

      </el-form-item>

      <el-form-item label="课程原价" prop="prePrice">

        <el-input v-model="course.prePrice" placeholder="请输入课程原件"></el-input>

      </el-form-item>

      <el-form-item label="课程现价" prop="currentPrice">

        <el-input v-model="course.currentPrice" placeholder="请输入课程现价"></el-input>

      </el-form-item>

      <el-form-item label="订阅须知" prop="notice">

        <el-input v-model="course.notice" placeholder="请输入订阅须知"></el-input>

      </el-form-item>

      <el-form-item label="咨询师" prop="consultantId">

        <el-select v-model="course.consultantId" placeholder="请选择咨询师">

          <el-option label="张晓岚" value="1"></el-option>

        </el-select>

      </el-form-item>

      <el-form-item label="课程类型" prop="categoryId">

        <el-select v-model="course.categoryId" placeholder="请选择课程类型">

          <el-option label="晓兰精选" value="1"></el-option>

          <el-option label="社会心理" value="2"></el-option>

          <el-option label="心理锻炼" value="3"></el-option>

          <el-option label="成长焦虑" value="4"></el-option>

        </el-select>

      </el-form-item>

    </el-form>

    <template #footer>

      <span class="dialog-footer">

        <el-button @click="dialogVisible = false">取消</el-button>

        <el-button type="primary" @click="save">保存</el-button>

      </span>

    </template>

  </el-dialog>

</template>

<style scoped>

.container {

  display: flex;

  flex-direction: flex-start;

  gap: 10px;

}

.avatar-uploader {

  border: 1px dashed #d9d9d9;

  border-radius: 6px;

  cursor: pointer;

  position: relative;

  overflow: hidden;

  width: 120px;

  height: 120px;

  display: flex;

  align-items: center;

  justify-content: center;

}



.avatar-uploader:hover {

  border-color: #409eff;

}



.avatar {

  width: 100%;

  height: 100%;

  object-fit: cover;

}



.avatar-uploader-icon {

  font-size: 24px;

  color: #8c939d;

}



.video-uploader {

  border: 1px dashed #d9d9d9;

  border-radius: 6px;

  cursor: pointer;

  position: relative;

  overflow: hidden;

  width: 300px;

  height: 200px;

  display: flex;

  align-items: center;

  justify-content: center;

}



.video-uploader:hover {

  border-color: #409eff;

}



.video {

  width: 100%;

  height: 100%;

  object-fit: cover;

}



.video-uploader-icon {

  font-size: 24px;

  color: #8c939d;

}

</style>